﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Giraffe.Client.Common;
using Giraffe.Client.Common.Managers;
using Giraffe.Client.ConversationModule.History;
using Giraffe.Core.Model;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Composite.Regions;
using Giraffe.Client.Common.Constants;
using Giraffe.Client.ConversationModule.Answer;
using Giraffe.Core.Common;

namespace Giraffe.Client.ConversationModule
{
    public class ConversationVM: ViewModelBase
    {
        private readonly IConversation _conversation;
        private readonly IRegionManager _regionManager;
        private readonly IConversationManagerPresentation _conversationPresentation;
        private ConversationHistoryVM _conversationHistory;
        private AnswerVM _answer;
        private DelegateCommand<object> _closeCommand;


        public ConversationVM(IConversation conversation, IRegionManager regionManager, 
                              IConversationManagerPresentation conversationPresentation)
        {
            _conversation = conversation;
            _regionManager = regionManager;
            _conversationPresentation = conversationPresentation;
            _conversationHistory = ObjectProvider.Resolve<ConversationHistoryVM>(new Tuple<string, object>("conversation", conversation));
            _answer = ObjectProvider.Resolve<AnswerVM>(new Tuple<string, object>("conversation", conversation));

            _closeCommand = new DelegateCommand<object>(CloseCommandExecute);

        }

        public void Init()
        {
            IApplicationProxy proxy = ObjectProvider.Resolve<IApplicationProxy>();
            if (!proxy.UIDispatcher.CheckAccess())
            {
                proxy.UIDispatcher.Invoke((Action)Init);
                return;
            }
            _regionManager.Regions[RegionNames.ConverstionHistoryPanel].Add(_conversationHistory);
            _regionManager.Regions[RegionNames.ConversationAnswerPanel].Add(_answer);
        }
        //public void Start()
        //{
        //    _regionManager.Regions[RegionNames.ConverstionHistoryPanel]
        //}

        internal string Answer
        {
            get
            {
                return _answer.Text;
            }
            set
            {
                _answer.Text = value;
            }
        }

        public ICommand CloseCommand
        {
            get
            {
                return _closeCommand;
            }
        }

        private void CloseCommandExecute(object obj)
        {
            _conversationPresentation.CloseConversation(_conversation);
        }
    }
}
